package cn.enjoy.wx.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.enjoy.tool.api.R;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author K
 * @date 2022-04-14 16:05
 */
@RestController
public class WxMaController {

    @Resource
    private WxMaService wxMaService;


    /**
     * 获取微信授权信息
     *
     * @param code 授权码
     */
    @RequestMapping(value = "/wechatSession", method = RequestMethod.POST)
    public R<WxMaJscode2SessionResult> wechatSession(@RequestParam String code) throws WxErrorException {
        //获取openId、unionid、session_key
        WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code);
        return R.data(sessionInfo);
    }

    /**
     * 小程序手机号登录
     */
//    @ApiOperation("小程序手机号登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sessionKey", value = "sessionKey", paramType = "query", dataType = "string", required = true),
            @ApiImplicitParam(name = "encryptedData", value = "加密串", paramType = "query", dataType = "string", required = true),
            @ApiImplicitParam(name = "iv", value = "偏移量", paramType = "query", dataType = "string", required = true)
    })
    @RequestMapping(value = "/wechatLogin", method = RequestMethod.POST)
    @ResponseBody
    public R<WxMaPhoneNumberInfo> wechatLogin(HttpServletRequest request,
                         @RequestParam String sessionKey,
                         @RequestParam String encryptedData,
                         @RequestParam String iv) {
        WxMaPhoneNumberInfo phoneInfo = wxMaService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);
        return R.data(phoneInfo);
    }

}
